package org.spbsu.apco.testing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spbsu.apco.client.Client;
import org.spbsu.apco.server.ApplicationContextProvider;
import org.spbsu.apco.server.EmbeddedServer;
import org.spbsu.apco.server.broker.impl.BrokerImpl;
import org.spbsu.apco.server.taskset.TaskSetEmitter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * User: solozobov
 * Date: 17.11.12
 */

public class Main {

    private static final Logger LOG = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        if (stringIndexInArray("-server", args) >= 0) {
            EmbeddedServer.main(new String[0]);

            final int index = stringIndexInArray("-testfile", args);

            final String testFile;
            if (index >= 0 && args.length >= index) {
                testFile = args[index + 1];
            } else {
                testFile = "testing.xml";
            }

            final ApplicationContext context = new ClassPathXmlApplicationContext(testFile);
            final TaskSetEmitter taskSetEmitter = context.getBean("taskSetEmitter", TaskSetEmitter.class);
            final BrokerImpl broker = ApplicationContextProvider.getApplicationContext().getBean("broker", BrokerImpl.class);
            taskSetEmitter.setBroker(broker);
            taskSetEmitter.start();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String clientParameter = findStringThatMatchesPrefix("-client", args);
        if (clientParameter != null) {
            int clientsNumber = 1;
            if (clientParameter.split("=").length==2) {
                clientsNumber = Integer.valueOf(clientParameter.split("=")[1]);
            }
            for (int client=0; client<clientsNumber; client++ )
                Client.start();
        }

        //noinspection InfiniteLoopStatement
        while(true) {
            try {
                Thread.sleep(10 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    private static int stringIndexInArray(final String text, final String[] array) {
        for (int i = 0; i < array.length; i++) {
            if (text.equals(array[i])) {
                return i;
            }
        }
        return -1;
    }

    private static String findStringThatMatchesPrefix(final String prefix, final String[] array) {
        for (String s : array) {
            if (s.startsWith(prefix))
                return s;
        }
        return null;
    }
}
